package com.zc.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.type.TypeFactory;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @description:
 * @author: cong
 * @create: 2024/8/1
 */
@Data
@NoArgsConstructor
public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
    public static final Charset DefaultCharset = StandardCharsets.UTF_8;
    private Class<T> clazz;

    static {
        ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
    }
    public FastJsonRedisSerializer(Class<T> clazz) {
        super();
        this.clazz = clazz;
    }


    @Override
    public byte[] serialize(T value) throws SerializationException {
        if (value == null){
            return new byte[0];
        }
        return JSON.toJSONString(value, SerializerFeature.WriteClassName).getBytes(DefaultCharset);
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length <= 0) {
            return null;
        }
        String s = new String(bytes, DefaultCharset);
        return JSON.parseObject(s, clazz);

    }

    public JavaType getJavaType(Class<?> clazz) {
        return TypeFactory.defaultInstance().constructType(clazz);
    }
}
